﻿using ADODB;
using fuzhu;
using LH.Model.PU;
using LH.Model.ST;
using SqlSuarEntity;
using SqlSugar;
using System.Data;
using U8COWeb;
using XXX.Bo;
using XXX.Common;
using XXX.Models;
using XXX.Models.XXXEntities;
using ZDEntity;
using static System.Runtime.CompilerServices.RuntimeHelpers;

namespace Yonyou.U8.BO
{

    public class RdRecord08VM : ST_Rdrecord08
    {
        //当前的数据库连接字符串
        public string conStr { get; set; }
        public string xmlConfig { get; set; }
        public bool bWMS = false;
        public string cDatabase = "";

        public RdRecord08VM(Head head, List<Body> bodies) : base(head, bodies)
        {
            //conStr
            conStr = CanShu.conStr;
            //初始化定义xmlconfig
            xmlConfig = XmlOperation.GetConfigXML();
        }
         


        public RetModel2 AddVerify()
        {

            string idcheck = "";
            if (Exists(ref idcheck))
            {
                return DBService.ReErrObject($"当前单据号{this.head.ccode}已存在");
            }
            foreach (Body body in bodies)
            {
                body.editprop = "A";
            }

            string cRe = GetAddInfo();
            if (cRe != "ok")
            {
                return DBService.ReErrObject("获取基础信息失败:" + cRe);
            }
            SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            });
            InventoryVM inventoryVM = new InventoryVM();
            HashSet<string> uniqueCinvCodes = new HashSet<string>();
            foreach (Body body in bodies)
            {
                body.editprop = "A"; // 设置 editprop 属性
                if (!string.IsNullOrEmpty(body.cinvcode))
                {
                    uniqueCinvCodes.Add(body.cinvcode);
                }
            }
            try
            {
                
               
                //不是wms生成的，检查单据号是否存在
                if (!bWMS && Exists(ref idcheck))
                {
                    throw new Exception("当前其他入库单号已存在");
                }

                // Step 1: 收集所有唯一的 cinvcode 
                inventoryVM.HandlerTopQty(db, uniqueCinvCodes);
                if (!Rdrecord08DALCO.AddVerifyRdrecord08(this, xmlConfig, out string err, out string id, out string ccode))
                {
                    //审核失败后，检查是否有采购入库单生成，如果有，则删除
                    string cerr2 = "";
                    if (!string.IsNullOrEmpty(id))
                    {
                        Rdrecord08DALCO.VerifyRdrecord08(id, xmlConfig, "delete", out cerr2);
                    }

                    throw new Exception("新增失败：" + err);
                }
                else
                {

                     
                        DateTime dDate = DbHelper.GetDbDate(head.ddate);
                        int iid = DbHelper.GetDbInt(id);
                    db.Updateable<RdRecord08>()
             .SetColumns(u => new RdRecord08()
             {
                 dVeriDate = dDate,
                 cHandler = head.cmaker
             })
             .Where(u => u.ID == iid)
             .ExecuteCommand();
                    //不是wms的情况，检查单据号是不是传入的单据号（单据编码选项是 相同的就自动生成）。 如果不是，删除
                    //if (!bWMS)
                    //    {

                    //        if (ccode != head.ccode && head.ccode != WMSPara.rd01Code)
                    //        {
                    //            //单据编码选项判断
                    //            string sql = string.Format(@"Select  bRepeatReDo  From VoucherNumber Where CardNumber='0301'");
                    //            int iRepeat = DbHelper.GetDbInt(db.Ado.GetScalar(sql));
                    //            if (iRepeat == 1)
                    //            {
                    //                string cerr2 = "";
                    //                Rdrecord08DALCO.VerifyRdrecord08(id, xmlConfig, "unverify,delete", out cerr2);
                    //            throw new Exception("单据已生成，重复");
                    //            }
                    //        }
                    //    }
                    //    else
                    //    {
                    //        //wms的情况，因为保存是无单据号，根据传入的parentid进行判断。默认字段使用扩展自定义项10
                    //        string cParentid = head.cdefine10;
                    //        if (!string.IsNullOrEmpty(cParentid))
                    //        {
                    //            //检查cParentid 是否存在
                    //            string sqlcx = string.Format(@"select count(*) sl from RdRecord08 a  where  a.cdefine10='{0}' and a.id <>'{1}'", cParentid, id);
                    //            int icntUniq = DbHelper.GetDbInt(db.Ado.GetScalar(sqlcx));
                    //            if (icntUniq > 0)
                    //            {
                    //                Rdrecord08DALCO.VerifyRdrecord08(id, xmlConfig, "unverify,delete", out _);
                    //            throw new Exception("之前单据已生成，重复");
                    //            }
                    //        }

                    //    }

                }
                //生成的id赋值
                head.id = id;
                inventoryVM.UnHandlerTopQty(db, uniqueCinvCodes);
                return DBService.ReOKObject(ccode);
                //}
            }
            catch (Exception ex)
            {
                inventoryVM.UnHandlerTopQty(db, uniqueCinvCodes);
                return DBService.ReErrObject(ex.Message);
            }

        }


        /// <summary>
        /// 其他入库单 弃审并删除
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RetModel2 UnverifyDelete()
        {
            try
            {
                string ID = "";
                if (!Exists(ref ID))
                {
                    return DBService.ReOKObject("当前单据号已删除");
                }
                //else
                //{
                //    head.id = ID;
                //}
                if (!Rdrecord08DALCO.VerifyRdrecord08(ID, xmlConfig, "unverify,delete", out string err))
                {
                    return DBService.ReErrObject("弃审失败：" + err);
                }

                return DBService.ReOKObject(head.ccode + "删除完成");
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }

        /// <summary>
        /// 其他入库单 弃审 ，不删除，再调拨单弃审的时候用
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public RetModel2 Unverify()
        {
            try
            {
                //string ID = "";
                //if (!Exists(ref ID))
                //{
                //    return DBService.ReOKObject("当前单据号已删除");
                //}

                if (!Rdrecord08DALCO.VerifyRdrecord08(head.id, xmlConfig, "unverify", out string err))
                {
                    return DBService.ReErrObject("弃审失败：" + err);
                }

                return DBService.ReOKObject(head.ccode + "弃审完成");
                //}
            }
            catch (Exception ex)
            {
                return DBService.ReErrObject(ex.Message);
            }
        }
        /// <summary>
        /// 其他入库单
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public RdRecord08VM GetAddEntity(API_Rdrecord obj, ref string cErr)
        {

            try
            {
                ST_Rdrecord08.Head head = new ST_Rdrecord08.Head
                {
                    bWireless = "1",
                    cvouchtype = "08",
                    cbustype = "其他入库",
                    csource = "库存",
                    ccode = obj.cCode,
                    cwhcode = obj.cWhCode,
                    crdcode = obj.cRdCode,
                    brdflag = "1",
                    //cdefine1 = obj.cCode,
                    ddate = DbHelper.GetDbDate(obj.dDate).ToString("yyyy-MM-dd"),
                    cpersoncode = obj.cPersonCode,
                    cdepcode = obj.cDepCode,
                    cmaker = obj.cMaker,
                    cvencode = obj.cVenCode,
                    dveridate = DbHelper.GetDbDate(obj.dDate).ToString("yyyy-MM-dd"),
                    chandler = obj.cHandler,
                    cmemo = obj.cMemo,

                    iswfcontrolled = "0",
                    vt_id = "67",
                    bomfirst = "0",
                    iPrintCount = "0",
                    cdefine1 = obj.cDefine1,
                    cdefine2 = obj.cDefine2,
                    cdefine3 = obj.cDefine3,
                    cdefine4 = obj.cDefine4,
                    cdefine5 = obj.cDefine5,
                    cdefine6 = obj.cDefine6,
                    cdefine7 = obj.cDefine7,
                    cdefine8 = obj.cDefine8,
                    cdefine9 = obj.cDefine9,
                    cdefine10 = obj.cDefine10,
                    cdefine11 = obj.cDefine11,
                    cdefine12 = obj.cDefine12,
                    cdefine13 = obj.cDefine13,
                    cdefine14 = obj.cDefine14,
                    cdefine15 = obj.cDefine15,
                    cdefine16 = obj.cDefine16,
                };


                List<LH.Model.ST.ST_Rdrecord08.Body> bodies = new List<LH.Model.ST.ST_Rdrecord08.Body>();
                if (obj.itemList != null && obj.itemList.Count > 0)
                {
                    using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                    {
                        ConnectionString = conStr,
                        DbType = SqlSugar.DbType.SqlServer,
                        IsAutoCloseConnection = true
                    }))
                    {


                        int i = 0;
                        foreach (var item in obj.itemList)
                        {
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.iQuantity)))
                            {
                                throw new Exception("数量不能为空");
                            }
                            if (string.IsNullOrEmpty(DbHelper.GetDbString(item.cInvCode)))
                            {
                                throw new Exception("存货编码不能为空");
                            }

                            i++;
                            ST_Rdrecord08.Body body = new ST_Rdrecord08.Body
                            {

                                cinvcode = item.cInvCode,
                                cfree1 = item.cFree1,
                                cfree2 = item.cFree2,
                                cfree3 = item.cFree3,
                                cfree4 = item.cFree4,
                                irowno = i.ToString(),
                                iquantity = DbHelper.GetDbString(item.iQuantity),
                                cbatch = item.cBatch,
                                cposition = item.cPosCode,
                                inum = DbHelper.GetDbString(item.iNum),
                                cbmemo = item.cBMemo,
                                citemcode = item.cItemCode,
                                citemcname = item.cItem_Name,
                                citem_class = item.cItem_Class,


                                //33自定义项作为mes行id
                                cdefine33 = item.cRowId,

                                //从22 写到37
                                cdefine22 = item.cDefine22,
                                cdefine23 = item.cDefine23,
                                cdefine24 = item.cDefine24,
                                cdefine25 = item.cDefine25,
                                cdefine26 = item.cDefine26,
                                cdefine27 = item.cDefine27,
                                cdefine28 = item.cDefine28,
                                cdefine29 = item.cDefine29,
                                cdefine30 = item.cDefine30,
                                cdefine31 = item.cDefine31,
                                cdefine32 = item.cDefine32,

                                cdefine34 = item.cDefine34,
                                cdefine35 = item.cDefine35,
                                cdefine36 = item.cDefine36,
                                cdefine37 = item.cDefine37

                            };
                            //本次无关联单据
                            //if (cSource == "生产订单")
                            //{
                            //    body.impoids = DbHelper.GetDbString(lstnew[i].autoid);
                            //}


                            bodies.Add(body);
                        }
                    }
                }



                RdRecord08VM model = new RdRecord08VM(head, bodies);
                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }

        }

        /// <summary>
        /// 传入json转换成PurchaseOrderVM
        /// </summary>
        /// <param name="json"></param>
        /// <param name="cErr"></param>
        /// <returns></returns>
        public RdRecord08VM GetCodeEntity(API_Rdrecord obj, ref string cErr)
        {

            try
            {

                ST_Rdrecord08.Head head = new ST_Rdrecord08.Head();
                head.ccode = obj.cCode;
                List<ST_Rdrecord08.Body> bodies = new List<ST_Rdrecord08.Body>();

                RdRecord08VM model = new RdRecord08VM(head, bodies);

                return model;

            }
            catch (Exception ex)
            {
                cErr = ex.Message;
                return null;
            }





        }
        /// <summary>
        /// 完善辅助计量单位
        /// </summary>
        /// <returns></returns>
        public string GetAddInfo()
        {
            try
            {
                using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
                {
                    ConnectionString = conStr,
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true
                }))
                {
                    for (int i = 0; i < bodies.Count; i++)
                    {
                        string cInvCode = bodies[i].cinvcode;
                        
                        
                        InvProperty invProperty = new InventoryVM().GetInvProperty(cInvCode, bodies[i].dmadedate, bodies[i].dvdate);
                        if (invProperty == null)
                        {
                            return string.Format("第{0}行物料{1}不存在", (i + 1).ToString(), cInvCode);
                        }
                        //iGroupType=0,无换算率，1,固定换算率，2,浮动换算率
                        if (invProperty.iGroupType != "0")
                        {
                            //辅助计量单位来源于来源单据，如果没有取库存单位
                            if (string.IsNullOrEmpty(bodies[i].cassunit))
                            {
                                bodies[i].cassunit = invProperty.cSTComUnitCode;
                            }

                          
                             bodies[i].iinvexchrate = invProperty.iChangRate;
                           
                            bodies[i].inum = (DbHelper.GetDbdecimal(bodies[i].iquantity) / DbHelper.GetDbdecimal(bodies[i].iinvexchrate)).ToString("0.000000");
                        }

                        //是否批次管理
                        if (!invProperty.bInvBatch)
                        {
                            bodies[i].cbatch = "";
                        }
                        else if (string.IsNullOrEmpty(bodies[i].cbatch))
                        {
                            return string.Format("第{0}行物料{1}有批次管理，未录入批次", (i + 1).ToString(), cInvCode);
                        }
                        //自由项，未处理

                        //有效期管理,根据生产日期或者失效日期推算 
                        if (invProperty.bInvQuality)
                        {
                            if (string.IsNullOrEmpty(bodies[i].dmadedate) && string.IsNullOrEmpty(bodies[i].dvdate))
                            {
                                return string.Format("第{0}行物料生产日期或者失效日期未录入", (i + 1).ToString());
                            }
                            else
                            {
                                bodies[i].dvdate = DbHelper.GetDbDate(invProperty.dVDate).ToString("yyyy-MM-dd");
                                bodies[i].imassdate = DbHelper.GetDbString(invProperty.iMassDate);
                                bodies[i].cmassunit = DbHelper.GetDbString(invProperty.cMassUnit);
                                bodies[i].dexpirationdate = DbHelper.GetDbDate(invProperty.dExpeireDate).ToString("yyyy-MM-dd"); ;
                                bodies[i].iexpiratdatecalcu = DbHelper.GetDbString(invProperty.iexpiratdatecalcu);
                            }


                        }


                    }

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }


            return "ok";
        }
        /// <summary>
        /// 检查其他入库单号是否存在
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Exists(ref string id)
        {
            if (head == null)
            {
                return false;
            }
            
            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                string sql = string.Format("select ID from RdRecord08 where ccode='{0}' ", head.ccode); 
                id = DbHelper.GetDbString(db.Ado.GetScalar(sql));

                 
                if (id == null)
                {
                    return false;
                }
                else
                {
                    head.id = id;
                    return true;
                }
    
            } 
        
        }

        /// <summary>
        ///   通过调拨单TVCode获取ID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool GetIdByTVCode(string cTVCode,ref string id)
        {
            if (head == null)
            {
                return false;
            }

            using (SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
            {
                ConnectionString = conStr,
                DbType = SqlSugar.DbType.SqlServer,
                IsAutoCloseConnection = true
            }))
            {
                var id8 = db.Queryable<RdRecord08>().Where(x=>x.cBusType=="调拨入库" &&x.cBusCode== cTVCode).Select(x=>x.ID).First();
                 
                if (id8 == null)
                {
                    return false;
                }
                else
                {
                    id = id8.ToString(); 
                    return true;
                }

            }

        }
    }
}
